package com.lajiaomian.springbootruijiwaimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lajiaomian.springbootruijiwaimai.common.BaseContext;
import com.lajiaomian.springbootruijiwaimai.common.R;
import com.lajiaomian.springbootruijiwaimai.dto.DishDto;
import com.lajiaomian.springbootruijiwaimai.pojo.Category;
import com.lajiaomian.springbootruijiwaimai.pojo.Dish;
import com.lajiaomian.springbootruijiwaimai.pojo.DishFlavor;
import com.lajiaomian.springbootruijiwaimai.service.impl.CategoryService;
import com.lajiaomian.springbootruijiwaimai.service.impl.DishFlavorService;
import com.lajiaomian.springbootruijiwaimai.service.impl.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lajiaomian
 * @create 2022-08-13-22:46
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 添加菜品
     * @param dishDto
     * @param session
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto, HttpSession session){
        Long empId = (Long) session.getAttribute("employee");
        BaseContext.setCurrId(empId);
        log.info(dishDto.toString());
        dishService.saveDishDto(dishDto);
        return R.success("添加成功");
    }

    /**
     * 分页显示菜品信息
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> list(Integer page,Integer pageSize,String name){
        log.info("菜品列表显示...page:{},pageSize:{},name:{}",page,pageSize,name);

        Page pageInfo = new Page(page,pageSize);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like(StringUtils.isNotEmpty(name),"name",name);
        wrapper.orderByDesc("update_time");
        dishService.page(pageInfo,wrapper);
        //新建并将dishPage的数据拷贝到DishDtoPage上
        Page DishDtoPage = new Page();
        //不拷贝records（就是查询出来的dish的List数据）
        BeanUtils.copyProperties(pageInfo,DishDtoPage,"records");
        //foreach循环pageInfo的rocords信息
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list =new ArrayList<>();
        for (Dish item:
                records) {
            DishDto dishDto = new DishDto();
            //将每个item赋值给dishDto
            BeanUtils.copyProperties(item,dishDto);
            //获取categoryId
            Long categoryId = dishDto.getCategoryId();
            //查询id对应的name
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            //设置到dishDto上
            dishDto.setCategoryName(categoryName); //此时dishDto具有dish和categoryName属性了
            list.add(dishDto);
        }
        DishDtoPage.setRecords(list);
        return R.success(DishDtoPage);
    }

    /**
     * 删除菜品/批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long[] ids){
        log.info("进行删除菜品操作，id为:{}",ids);
        for(Long id:ids){
            dishService.removeById(id);
        }
        return R.success("删除成功");
    }

    /**
     * 根据id获取菜品信息
     * @param ids
     * @return
     */
    @GetMapping("{ids}")
    public R<Dish> getById(@PathVariable("ids") Long ids){
        log.info("更新菜品:{}" ,ids);
        DishDto dishDto = dishService.getDishById(ids);
        return R.success(dishDto);
    }

    /**
     * 更新菜品
     * @param dishDto
     * @param session
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto,HttpSession session){
        Long empId = (Long) session.getAttribute("employee");
        BaseContext.setCurrId(empId);
        log.info("进行更新操作:{}",dishDto.toString());
        dishService.updateDishDto(dishDto);
        return R.success("更新成功");
    }

    /**
     * 禁用菜品
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> updateStatus0(Long[] ids){
        log.info("状态修改，ids：{}",ids);
        for(Long id : ids){
            Dish dish = dishService.getById(id);
            dish.setStatus(0);
            dishService.updateById(dish);
        }
        return R.success("状态修改成功");
    }

    /**
     * 启用菜品
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> updateStatus1(Long[] ids){
        log.info("状态修改，ids：{}",ids);
        for(Long id : ids){
            Dish dish = dishService.getById(id);
            dish.setStatus(1);
            dishService.updateById(dish);
        }
        return R.success("状态修改成功");
    }

    //http://localhost:8080/dish/list?categoryId=1397844263642378242
//    @GetMapping("/list")
//    public R<List<Dish>> list(Long categoryId){
//        log.info("展示categoryList，id：{}",categoryId);
//        QueryWrapper wrapper = new QueryWrapper();
//        wrapper.eq("category_id",categoryId);
//        List list = dishService.list(wrapper);
//        return R.success(list);
//    }
    //http://localhost:8080/dish/list?categoryId=1397844263642378242&status=1

    /**
     * 展示菜品信息
     * @param categoryId
     * @param status
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId,int status){
        log.info("展示categoryList，id：{},status:{}",categoryId,status);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,categoryId).eq(Dish::getStatus,status);
        List<Dish> dishList = dishService.list(wrapper);
        LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
        List<DishDto> dishDtoList = dishList.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            //设置categoryName属性
            Category category = categoryService.getById(categoryId);
            if(category!= null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //设置dishFlavorList属性
            Long dishId = dish.getId();
            wrapper1.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(wrapper1);
            wrapper1.clear();
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }

//    @GetMapping("/list")
//    public R<List<DishDto>> list(Dish dish){
//        log.info("展示菜品List：{}",dish);
//        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
//        //获取categoryId等于传过来的值且status==1的值
//        wrapper.eq(Dish::getCategoryId,dish.getCategoryId()).eq(Dish::getStatus,1);
//        //设置排序为修改时间的倒序
//        wrapper.orderByDesc(Dish::getUpdateTime);
//        //获取符合条件的集合
//        List<Dish> dishList = dishService.list(wrapper);
//        LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
//        List<DishDto> dishDtoList = dishList.stream().map(item -> {
//            DishDto dishDto = new DishDto();
//            BeanUtils.copyProperties(dish, dishDto);
//            //设置categoryName属性
//            Category category = categoryService.getById(dish.getCategoryId());
//            if(category!=null){
//                String categoryName = category.getName();
//                dishDto.setCategoryName(categoryName);
//            }
//            //设置dishFlavorList属性
//            Long dishId = dish.getId();
//            wrapper1.eq(DishFlavor::getDishId, dishId);
//            List<DishFlavor> dishFlavorList = dishFlavorService.list(wrapper1);
//            wrapper1.clear();
//            dishDto.setFlavors(dishFlavorList);
//            return dishDto;
//        }).collect(Collectors.toList());
//        return R.success(dishDtoList);
//    }
}
